<?php


namespace PolarisbackEndFrameRe\exception;

use Exception;
use PolarisbackEndFrameRe\api\log\Logger;

define('ENVIRONMENT', 'development');

class ExceptionProcessor
{    
    private $logger;

    public function __construct(Logger $logger)
    {
        $this->logger = $logger;
    }

    public function register()
    {
        set_exception_handler([$this, 'handle']);
    }

    public function handle(Exception $exception)
    {
        $this->logException($exception);
        $this->renderErrorPage($exception);
    }

    private function logException(Exception $exception)
    {
        $message = sprintf(
            "Uncaught exception '%s': %s in %s:%s",
            get_class($exception),
            $exception->getMessage(),
            $exception->getFile(),
            $exception->getLine()
        );
        $this->logger->error($message);
    }

    private function renderErrorPage(Exception $exception)
    {
        http_response_code(500);
        header('Content-Type: text/html; charset=utf-8');

        $errorMessage = $exception->getMessage();
        if (defined('ENVIRONMENT') && ENVIRONMENT === 'development') {
            // 在开发环境中显示详细的错误信息
            echo "<h1>Internal Server Error</h1>";
            echo "<p><strong>Exception:</strong> " . get_class($exception) . "</p>";
            echo "<p><strong>Message:</strong> " . htmlspecialchars($errorMessage) . "</p>";
            echo "<p><strong>File:</strong> " . htmlspecialchars($exception->getFile()) . "</p>";
            echo "<p><strong>Line:</strong> " . htmlspecialchars($exception->getLine()) . "</p>";
            echo "<pre>" . htmlspecialchars($exception->getTraceAsString()) . "</pre>";
        } else {
            // 在生产环境中显示简化的错误信息
            echo "<h1>Internal Server Error</h1>";
            echo "<p>Sorry, something went wrong. Please try again later.</p>";
        }
    }
}